package com.jiaquyun.jcyx.main.cart

import android.os.Bundle
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.GsonUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.MainBean
import com.jiaquyun.jcyx.entity.OrderDetails
import com.jiaquyun.jcyx.entity.PayInfo
import com.jiaquyun.jcyx.entity.PayResult
import com.jiaquyun.jcyx.jetpack.mode.OrderViewModel
import com.jiaquyun.jcyx.main.mine.MineOrderActivity
import com.module.lemlin.LoadingDialog
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_order_pay.*

class OrderPayActivity : OwnerViewModeActivity<OrderViewModel>() {

    companion object {
        private const val KEY_ORDER_DETAILS = "KEY_ORDER_DETAILS"
        fun open(orderDetails: OrderDetails) {
            val bundle = Bundle().apply {
                putSerializable(KEY_ORDER_DETAILS, orderDetails)
            }
            ActivityUtils.startActivity(bundle, OrderPayActivity::class.java)
        }
    }

    private val mOrderDetails: OrderDetails? by lazy {
        intent?.extras?.getSerializable(KEY_ORDER_DETAILS) as? OrderDetails
    }

    override fun viewModel(): OrderViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_order_pay

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, color = R.color.white, view = flOrderPayBar)
    }

    override fun initView() {

        ivAppBack.setOnClickListener { finish() }

        mOrderDetails?.let {
            fillData(it)
        }

        tvOrderPaySubmit.setOnClickListener {
            mOrderDetails?.let {
                viewModel.orderPay(it.id.toString(), "wechat")
            }
        }
    }

    override fun initViewMode() {
        viewModel.orderPayLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.START) {
                LoadingDialog.show(this, R.layout.dialog_load_style_1)
            } else if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
                LoadingDialog.dismiss()
            } else {
                LoadingDialog.dismiss()
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            if (data.isNeedPay) {
                val payInfo = GsonUtils.fromJson(data.payInfo.toString(), PayInfo::class.java)
                wxPayView(payInfo)
            } else {
                finish()
                ActivityUtils.finishActivity(CartSettlementActivity::class.java)
                MineOrderActivity.open()
            }
        })
    }

    private fun fillData(orderDetails: OrderDetails) {
        tvOrderPaySn.text = orderDetails.order_sn
        tvOrderPayGoodsPrice.text = "￥${orderDetails.goods_price}"
        tvOrderPayShippingPrice.text = "￥${orderDetails.shipping_price}"
        tvOrderPayCouponPrice.text = "￥${orderDetails.coupon_price}"
        tvOrderPayDiscountPrice.text = "￥${orderDetails.discount_price}"
        tvOrderPayIntegralPrice.text = "￥${orderDetails.integral_price}"
        tvOrderPayUserMoney.text = "￥${orderDetails.user_money}"
        tvOrderPayMoney.text = "￥${orderDetails.order_amount}"
    }


    /**
     * 拉起微信支付
     * */
    private fun wxPayView(entity: PayInfo) {
        val disposable: Disposable = Observable.just(WXAPIFactory.createWXAPI(this, null))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter {
                if (!it.isWXAppInstalled) {
                    toast("未安装微信")
                }
                it.isWXAppInstalled
            }
            .subscribe({ msgApi ->
                msgApi.registerApp("wx504428242c9715b6")
                msgApi.sendReq(PayReq().also {
                    it.appId = "wx504428242c9715b6"
                    it.partnerId = entity.partnerid
                    it.prepayId = entity.prepayid
                    it.packageValue = entity.`package`
                    it.nonceStr = entity.noncestr
                    it.sign = entity.sign
                    it.timeStamp = entity.timestamp
                    it.extData = "0"
                })
            }, {
                toast("微信支付-${it.message ?: "未知错误"}")
            })
        viewModel.dispose.add(disposable)
    }

    override fun onEventMainThread(any: Any) {
        if (any !is MainBean<*, *>) {
            return
        }
        if (any.type !is PayResult) {
            return
        }
        if (any.type == PayResult.SUCCESS) {
            finish()
            ActivityUtils.finishActivity(CartSettlementActivity::class.java)
            MineOrderActivity.open()
        } else {
            toast(any.type.desc)
        }
    }

}